<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Posts extends CI_Controller {

	public function __construct() {
		parent::__construct();
	}

	public function index() {
		redirect();
	}
	
	public function create_post() {

		$data['title'] = "New Post | PostLeng";
		// $this->load->library('math_question');
		// $this->load->library('session');
		
		// $this->load->helper('form');

		// $questionOne = $this->math_question->questionOne();
		// $questionTwo = $this->math_question->questionTwo();

		// $this->session->set_flashdata('questionOne', $questionOne);
		// $this->session->set_flashdata('questionTwo', $questionTwo);

		// $data['math_question'] = "What is {$questionOne} + {$questionTwo}?";

		// $this->form_validation->set_rules('newpost_description', 'Math Question', 'required');

		$data['tags'] = $this -> mod_tag -> select_tag();
		$data['tag'] = $this -> mod_tag -> select_tag_random();

		$this->load->helper("captcha");
		$this->form_validation->set_rules('captcha','captcha','callback_validate_captcha');

		if($this->form_validation->run()===FALSE){
			$vals = array( 'img_path' => './templates/front_end/images/captcha/',
				'img_url' => base_url().'templates/front_end/images/captcha/', 
				'font_path'=>base_url().'templates/front_end/font/VeraBd.ttf/',
				'img_width' => '130', 
				'img_height' => 30, 
				'border' => 0, 
				'expiration' => 7200); 
			
 // create captcha image 
			$cap = create_captcha($vals); 
 // store image html code in a variable 
			$data['image'] = $cap['image']; 
			if (isset($this -> session -> userdata['image']))
				{ if (file_exists("./templates/front_end/images/captcha/" . $this -> session -> userdata['image']))
			unlink("./templates/front_end/images/captcha/" . $this -> session -> userdata['image']); 
		} 
		$this -> session -> set_userdata('captcha', $cap['word']);
		$this -> session -> set_userdata('image', $cap['time'] . '.jpg');	

		$this -> load -> view(F_MASTER . 'index', $data);
	}else{
		$select_tag = $this->input->post('select_tag');
		$random_key =  random_string('alnum', 12);
		$img_url =$this->input->post('img_url');
		$desc =$this->input->post('newpost_description');

		$post_url = $this->input->post('embedUrl');
		$post_url_Image = $this->input->post('embedImg_url');
		$create_date = null;

		$this->load->model('mod_post');
		$post_id=$this->mod_globals->insert_get_last_id(PREFIX_TABLE."posts",array('img_name' => $img_url,'embed_code'=> htmlentities($post_url),'description'=>$desc,'key_posts'=>$random_key,'embed_img'=>$post_url_Image,'created_date'=>$create_date));

		foreach ($select_tag as  $value) {
			$this->mod_globals->insert(PREFIX_TABLE."post_has_tags",array("use_tag_id"=>$value,"use_post_id"=>$post_id));
		}
		redirect(base_url());
	}

}



	// Insert new post
public function insert_newpost(){

}
public function most_read(){

	$data['title'] = "PostLeng | Poppular Post";
	$data['open_graph'] = '<meta property="og:site_name" content="Post Leng.com" />
	<meta property="og:title" content="Description of the image:" />
	<meta property="og:type" content="article" />
	<meta property="og:url" content="http://postleng.com" />
	<meta property="og:image" content="" />
	<meta property="og:locale" content="en_US" />
	<meta property="og:description" content="Post leng is free post for everyone. You can post what ever you wanted!" />';
	$data['tag'] = $this -> mod_tag -> select_tag_random();
	$data['post_record'] = $this -> mod_post -> count_most_read();
	$this -> load -> view(F_MASTER . 'index', $data);

}
public function view_most_read(){
		$items_per_group = 20;//sanitize post value
		$group_number = filter_var($_POST["group_no"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
		if (!is_numeric($group_number)) {
			header('HTTP/1.1 500 Invalid number!');
			exit();
		}
		$position = ($group_number * $items_per_group);
		$results= $this ->mod_globals-> select_join(PREFIX_TABLE.'post_has_tags', array(PREFIX_TABLE.'posts' => array('use_post_id' => 'post_id'),PREFIX_TABLE.'tags'=> array('use_tag_id'=>'tag_id')),'inner',array(PREFIX_TABLE.'posts.status' => 1),$items_per_group.",".$position,"count_click_views DESC");

		
		if ($results) {
				//output results from database
			echo '<ul class="thumbnails">';
			foreach ($results->result() as $row) {
				if($row -> count_click_views<=0){
					$views="ដង ";
				}else{
					$views="ដង ";
				}
				$str = $row -> description;
					$v_random = rand(1,2);// random class in css
					$col = "";
					if ($v_random == 1) {
						$col = "col-md-2";
					} else {
						$col = "col-md-3";
					} 
					////////// text /////////////////////////
					echo '<div class="' . $col . '" id="thumnail_over" style="margin-left: 4px; margin-right: 10px; padding-left: 0; padding-right: 0;">';
					if  ($row -> img_name == NULL && $row -> embed_code==NULL && $row -> embed_img ==NULL ) {
						$str = substr($str, 0,150)."...";
						echo '<li class="thumbnail" id="speak">';
						//echo '<aside class="pquote">';
						
						echo '<a href="#" data-toggle="modal" onclick="popUpText(this)" row_baseUrl="'.base_url().'tags/get-data-by-tag/'.'" row_key_code="" row_tag_text="'."".'" data_count_click_text="' . $row -> count_click_views . '" data-target="#basicModalfortext" class="popup-modal" row_id_text="' . $row -> post_id . '" row_desc_text="' . $row -> description . '"><p style="color: #33536D;">' .'<q>&nbsp;'. $str.'&nbsp;</q>' . '</p></a>';
						
						//echo '</aside>';
						echo '<span class="caption simple-caption" style="bottom: -52px !important;">';

						echo '<p class="bgdescolor">';
						echo '<span class="text-icons"><i class="glyphicon glyphicon-eye-open"></i>បង្ហាញ​'.'<span class="counting_view_text'.$row -> post_id.'">'.' '.$row->count_click_views.'</span>'.' '.'<span>'.$views.'<span> ';
						$querys= $this ->mod_globals-> select_join(PREFIX_TABLE.'post_has_tags', array(PREFIX_TABLE.'posts' => array('use_post_id' => 'post_id'),PREFIX_TABLE.'tags'=> array('use_tag_id'=>'tag_id')),'inner',array(PREFIX_TABLE.'posts.status' => 1, 'use_post_id'=>$row -> post_id));
						foreach ($querys->result() as $key) {
							echo '<a class="badge" style="background: #fff !important; color: #728EA4;" href="'.base_url()."tags/get-data-by-tag/".$key->key_tags.'">'.$key->name.'</a>';
						}
						
						echo '<div >'.$row->embed_code.'</div>';
						echo '</p>';
						echo '</span>';
						echo '</a>';
						echo '</li>';

					//// Upload image //////////////
					} else if($row -> img_name!=NULL && $row -> embed_code==NULL && $row -> embed_img ==NULL) {
						if (strlen($str) > 30 && strlen($str) < 101) {
							$str = substr($str, 0, 30) . '...';
						}
						echo '<li class="thumbnail" >';
						echo '<a href="#" class="tag_name_herf" row_baseUrl="'.base_url().'tags/get-data-by-tag/'.'" row_key_code="'." ".'" row_tag="'." ".'" data-toggle="modal" onclick="popUpDetail(this)" data_count_click="' . $row -> count_click_views . '" data-target="#basicModal" class="popup-modal" 
						row_id="' . $row -> post_id . '" tag_id="'.$row->tag_id.'" row_des="' . $row -> description . '" row_img="' . $row -> img_name . '""><img src="' . $row -> img_name . '" /></a>';
						echo '<p class="text_description">'.$str.'</p><br />';
						echo '<span class="caption simple-caption">';
						echo '<p class="bgdescolor">';
						echo '<span class="text-icons"><i class="glyphicon glyphicon-eye-open"></i>បង្ហាញ​'.'<span id="count_related" class="counting_view'.$row -> post_id.'">'.' '.$row->count_click_views.'</span>'.' '.'<span>'.$views.'|<span> ';
						$querys= $this ->mod_globals-> select_join(PREFIX_TABLE.'post_has_tags', array(PREFIX_TABLE.'posts' => array('use_post_id' => 'post_id'),PREFIX_TABLE.'tags'=> array('use_tag_id'=>'tag_id')),'inner',array(PREFIX_TABLE.'posts.status' => 1, 'use_post_id'=>$row -> post_id));
						foreach ($querys->result() as $key) {
							echo '<a class="badge" style="background: #fff !important; color: #728EA4;" href="'.base_url()."tags/get-data-by-tag/".$key->key_tags.'">'.$key->name.'</a>';
						}
						echo '</p>';
						echo '</span>';
						echo '</a>';
						echo '</li>';;

					//// embed image from other url  ///////
					} else if($row -> embed_img!=NULL && $row -> embed_code==NULL && $row ->  img_name ==NULL) {
						if (strlen($str) > 30 && strlen($str) < 101) {
							$str = substr($str, 0, 30) . '...';
						}
						echo '<li class="thumbnail" >';
						echo '<p class="text_description">'.$str.'</p>';
						echo '<a href="#" class="tag_name_herf" row_baseUrl="'.base_url().'tags/get-data-by-tag/'.'" row_key_code="'."".'" row_tag="'."".'" data-toggle="modal" onclick="popUpDetail(this)" data_count_click="' . $row -> count_click_views . '" data-target="#basicModal" class="popup-modal" 
						row_id="' . $row -> post_id . '" tag_id="'.$row->tag_id.'" row_des="' . $row -> description . '" row_img="' . $row -> embed_img . '""><img src="' . $row -> embed_img . '" /></a>';
						
						echo '<span class="caption simple-caption">';
						
						echo '<p class="bgdescolor">';
						echo '<span class="text-icons"><i class="glyphicon glyphicon-eye-open"></i>បង្ហាញ​'.'<span class="counting_view'.$row -> post_id.'">'.' '.$row->count_click_views.'</span>'.' '.'<span>'.$views.'|<span> ';
						$querys= $this ->mod_globals-> select_join(PREFIX_TABLE.'post_has_tags', array(PREFIX_TABLE.'posts' => array('use_post_id' => 'post_id'),PREFIX_TABLE.'tags'=> array('use_tag_id'=>'tag_id')),'inner',array(PREFIX_TABLE.'posts.status' => 1, 'use_post_id'=>$row -> post_id));
						foreach ($querys->result() as $key) {
							echo '<a class="badge" style="background: #fff !important; color: #728EA4;" href="'.base_url()."tags/get-data-by-tag/".$key->key_tags.'">'.$key->name.'</a>';
						}
						echo '</p>';
						echo '</span>';
						echo '</a>';
						echo '</li>';

					/////////////////// video ////////////////////////////
					} else if($row -> img_name==NULL && $row -> embed_img ==NULL && $row -> embed_code!=NULL) {
						
						$ser = array();
						$ser[] = $row -> embed_code;
						?>
						<script type="text/javascript">
							get_video();
							function get_video()
							{
								$(".oembed").oembed(null, 
								{
									embedMethod: "append", 
									maxWidth: 424,
									maxHeight: 268,
									vimeo: { autoplay: true, maxWidth: 200, maxHeight: 200}			
								});
								var array_embed_code = <?php echo json_encode($ser,JSON_UNESCAPED_SLASHES); ?>; /// convert to array javscript and escap slashes
								$("#stexpand"+<?php echo $row->post_id; ?>).oembed(array_embed_code[0]); /// validate url by concerting to video 	
							}
						</script>
						<?php
						$description = substr($row -> description, 0,30).'...';
						echo '<div onclick="emebd_video_image(this)" row_baseUrl="'.base_url().'tags/get-data-by-tag/'.'" row_key_code="'."".'" row_tag_name_embed="'."".'" row_count_click_embed="'.$row -> count_click_views.'" row_post_id_embed="'.$row -> post_id.'" row_code_url="'.$row->embed_code.'">';
						echo '<li class="thumbnail" >';
						echo '<span id="stexpand'.$row->post_id.'">' ;

						echo '<p>'.$description.'</p>';
						echo '</span>';
						echo '<br />';
						echo '<span class="caption simple-caption">';

						echo '<p class="bgdescolor">';
						echo '<span class="text-icons"><i class="glyphicon glyphicon-eye-open"></i>បង្ហាញ​'.'<span class="counting_view_embed'.$row -> post_id.'">'.' '.$row->count_click_views.'</span>'.' '.'<span>'.$views.'|<span> ';
						$querys= $this ->mod_globals-> select_join(PREFIX_TABLE.'post_has_tags', array(PREFIX_TABLE.'posts' => array('use_post_id' => 'post_id'),PREFIX_TABLE.'tags'=> array('use_tag_id'=>'tag_id')),'inner',array(PREFIX_TABLE.'posts.status' => 1, 'use_post_id'=>$row -> post_id));
						foreach ($querys->result() as $key) {
							echo '<a class="badge" style="background: #fff !important; color: #728EA4;" href="'.base_url()."tags/get-data-by-tag/".$key->key_tags.'">'.$key->name.'</a>';
						}
						echo '</p>';
						echo '</span>';
						echo '</a>';
						echo '</li>';
						echo '</div>';
					}
					echo '</div>';
				}
				//end of result set
			}
			echo '</ul>';
		}

		function test()
		{

			$this->load->library('math_question');

			$this->load->helper('form');


			$questionOne = $this->math_question->questionOne();
			$questionTwo = $this->math_question->questionTwo();

			$this->session->set_flashdata('questionOne', $questionOne);
			$this->session->set_flashdata('questionTwo', $questionTwo);

			$data['math_question'] = "What is {$questionOne} + {$questionTwo}?";

			$this->form_validation->set_rules('math_question', 'Math Question', 'callback_math_question');


			if($this->form_validation->run() == FALSE)
			{
				$data['tags'] = $this -> mod_tag -> select_tag();
				$data['tag'] = $this -> mod_tag -> select_tag_random();
				$this -> load -> view(F_MASTER . 'index', $data);

			}
			else
			{
				echo "success";
			}
		}



		function math_question()
		{
			$user_answer = $this->input->post('math_question');
			$questionOne = $this->session->flashdata('questionOne');
			$questionTwo = $this->session->flashdata('questionTwo');

			$correct_answer = $questionOne + $questionTwo;

			if($user_answer != $correct_answer)
			{
				$this->form_validation->set_message('math_question', 'Your answer to the math question was incorrect');
				return FALSE;
			} else {
				return TRUE;
			}
		}

		public function validate_captcha() { 
			if ($this -> input -> post('captcha') != $this -> session -> userdata('captcha'))
			{

				$this -> form_validation -> set_message('validate_captcha', "<p style='color:red'>លេខ​​​កូដ​ដែល​អ្នក​បញ្ជូល​មិន​ត្រឹម​ត្រូវ​ទេ</p>"); 
				return false; 
			} else { 
				return true; 
			}
		}

	}
